<?php
/**
 * Created by PhpStorm.
 * User: wuchunyin
 * Date: 2018/11/6
 * Time: 18:52
 */
namespace app\index\service;

use think\facade\Env;

class ExcelService{

    function __construct(){
        /*导入phpExcel核心类 */
        require_once Env::get('extend_path').'PHPExcel/PHPExcel.php';
//        require_once APP_PATH . 'PHPExcel/PHPExcel/Writer/Excel5.php';     // 用于其他低版本xls
        require_once Env::get('extend_path').'PHPExcel/PHPExcel/Writer/Excel2007.php'; // 用于 excel-2007 格式
    }

    public function exportExcel($data,$excelFileName,$fieldList){
        if(empty($data) || !is_array($data)){
            die("data is not array or data is empty");
        }
        $this->__construct();
        /* 实例化类 */
        $objPHPExcel = new \PHPExcel();

        /* 设置输出的excel文件为2007兼容格式 */
        //$objWriter=new PHPExcel_Writer_Excel5($objPHPExcel);//非2007格式
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);

        /* 设置当前的sheet */
        $objPHPExcel->setActiveSheetIndex(0);

        $objActSheet = $objPHPExcel->getActiveSheet();

        $colList = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T'
        ,'U','V','W','X','Y','Z','AA','AB','AC','AD','AE','AF','AG','AH','AI','AJ','AK','AL','AM','AN','AO','AP','AQ'
        ,'AR','AS','AT','AU','AV','AW','AX','AY','AZ','BA','BB','BC','BD','BE','BF','BG','BH','BI','BJ','BK'];


        //填入表头
        foreach ($fieldList as $key=>$value) {
            $objPHPExcel->getActiveSheet()->setCellValue($colList[$key].'1', $value['title']);
        }

        /*设置宽度*/
        foreach ($colList as $key=>$value) {
            $objPHPExcel->getActiveSheet()->getColumnDimension($value)->setWidth(15);
        }

        foreach($data as $key => $value){
            /* excel文件内容 */
            $num = $key+2;
            // $value2=iconv("gbk","utf-8",$value2);
            foreach ($fieldList as $key=>$field) {
                $objActSheet->setCellValue($colList[$key].$num,$value[$field['field']]);
            }
        }

        /* 生成到浏览器，提供下载 */
        ob_end_clean();  //清空缓存
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header('Content-Disposition:attachment;filename="'.$excelFileName.'.xlsx"');
        header("Content-Transfer-Encoding:binary");

        $objWriter->save('php://output');
    }
}